package com.sc.base.common.spring.mvc;

import com.sc.base.apiutils.api.CommonErrorCode;
import com.sc.base.apiutils.api.ErrorCode;
import com.sc.base.apiutils.api.ErrorInfo;
import com.sc.base.common.spring.ApplicationConstant;
import com.sc.base.common.spring.ApplicationContextHolder;
import com.sc.base.common.spring.utils.ErrorInfoConverter;
import com.sc.base.common.spring.utils.ServletWebUtils;
import com.sc.base.common.utils.SpringViewUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author liubin
 * @Date 2017/5/15 15:02
 */
@Controller
public class AppErrorController {

    @Autowired(required = false)
    private ErrorInfoConverter errorInfoConverter;

    @RequestMapping("/401")
    public ModelAndView error401(HttpServletRequest request, HttpServletResponse response) {

        ErrorCode errorCode = CommonErrorCode.UNAUTHORIZED;
        ErrorInfo errorInfo = new ErrorInfo(errorCode, request.getRequestURI());

        return createErrorView(request, response, errorInfo, "401");
    }

    @RequestMapping("/404")
    public ModelAndView error404(HttpServletRequest request, HttpServletResponse response) {
        ErrorCode errorCode = CommonErrorCode.NOT_FOUND;
        ErrorInfo errorInfo = new ErrorInfo(errorCode, request.getRequestURI());

        return createErrorView(request, response, errorInfo, "404");
    }

    @RequestMapping("/500")
    public ModelAndView error500(HttpServletRequest request, HttpServletResponse response) {
        ErrorCode errorCode = CommonErrorCode.INTERNAL_ERROR;
        ErrorInfo errorInfo = new ErrorInfo(errorCode, request.getRequestURI());

        return createErrorView(request, response, errorInfo, "500");
    }


    protected ModelAndView createErrorView(HttpServletRequest request, HttpServletResponse response, ErrorInfo error, String viewName) {

        ApplicationConstant constant = ApplicationContextHolder.context.getBean(ApplicationConstant.class);
        if(constant.webProject || !ServletWebUtils.isNeedJsonResponse(request)) {
            Map<String, Object> map = new HashMap<>();
            map.put("errorInfo", error);
            return new ModelAndView(viewName, map);
        } else {
            return SpringViewUtils.createJsonErrorView(error, errorInfoConverter);
        }
    }



}

